package com.retoc.oawx.service.impl;

import cn.hutool.core.date.*;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.retoc.oawx.domain.CarUse;
import com.retoc.oawx.exception.OAException;
import com.retoc.oawx.mapper.MaterialsMapper;
import com.retoc.oawx.mapper.UserMapper;
import com.retoc.oawx.service.ApproveService;
import com.retoc.oawx.service.CarUseService;
import com.retoc.oawx.mapper.CarUseMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

/**
* @author retoc
* @description 针对表【tb_car_use】的数据库操作Service实现
* @createDate 2022-06-22 10:29:27
*/
@Service
public class CarUseServiceImpl extends ServiceImpl<CarUseMapper, CarUse>
    implements CarUseService{
    @Autowired
    UserMapper userMapper;

    @Autowired
    CarUseMapper carUseMapper;

    @Autowired
    MaterialsMapper materialsMapper;

    @Autowired
    ApproveService approveService;

    @Value("${oawx.receiveNotify}")
    private String receiveNotify;

    @Value("${workflow.urla}")
    private String workflow;

    @Override
    public int createCarUse(CarUse carUse) {
        if (!checkCarCanUse(carUse)){
            throw new OAException("该车辆该日期已被预约！");
        }
        int gmId = userMapper.searchGmId();
        if (gmId==carUse.getCreaterId()){
            carUse.setStatus(1);
        }
        int row = carUseMapper.createCarUse(carUse);
        if (row!=1){
            throw new OAException("创建用车单失败");
        }
        JSONObject json = new JSONObject();
        json.set("url", receiveNotify);
        json.set("createId", carUse.getCreaterId());
        int deptManagerId = userMapper.searchDeptManagerId(carUse.getCreaterId());
        json.set("managerId", deptManagerId);
        json.set("adId",4);
        Date startTime = carUse.getStartTime();
        Date endTime = carUse.getEndTime();
        long between = DateUtil.between(startTime, endTime, DateUnit.DAY);
        json.set("dates", startTime);
        json.set("days", between);
        json.set("types", "car");
        String url = workflow + "/car/carRequest";
        HttpResponse resp = HttpRequest.post(url).header("Content-Type", "application/json").body(json.toString())
                .execute();
        if (resp.getStatus() == 200) {
            JSONObject json1 = JSONUtil.parseObj(resp.body());
            JSONObject result = JSONUtil.parseObj(json1.getStr("result"));
            String instanceId = result.getStr("instanceId");
            HashMap param = new HashMap();
            param.put("uuid", carUse.getUuid());
            param.put("instanceId", instanceId);
            int row1 = carUseMapper.setInstanceId(param);
            if (row1!=1){
                throw new OAException("保存会议工作流失败");
            }
        }
        return row;
    }

    @Override
    public int updateCarUse(CarUse carUse) {
        if (!checkCarCanUse(carUse)){
            throw new OAException("该车辆该日期已被预约！");
        }
        CarUse old = carUseMapper.myselectById(carUse.getId());
        approveService.deleteProcess(old.getInstanceId());
        int row = carUseMapper.updateCarUse(carUse);
//        CarUse newCarUse = carUseMapper.myselectById(carUse.getId());

        JSONObject json = new JSONObject();
        json.set("url", receiveNotify);
        json.set("createId", old.getCreaterId());
        int deptManagerId = userMapper.searchDeptManagerId(old.getCreaterId());
        json.set("managerId", deptManagerId);
        json.set("adId",4);
        Date startTime = carUse.getStartTime();
        Date endTime = carUse.getEndTime();
        long between = DateUtil.between(startTime, endTime, DateUnit.DAY);
        json.set("dates", startTime);
        json.set("days", between);
        json.set("types", "car");
        json.set("driver",carUse.getDriver()==null?0:1);
        String url = workflow + "/car/carRequest";
        HttpResponse resp = HttpRequest.post(url).header("Content-Type", "application/json").body(json.toString())
                .execute();
        if (resp.getStatus() == 200) {
            JSONObject json1 = JSONUtil.parseObj(resp.body());
            JSONObject result = JSONUtil.parseObj(json1.getStr("result"));
            String instanceId = result.getStr("instanceId");
            HashMap param = new HashMap();
            param.put("uuid", old.getUuid());
            param.put("instanceId", instanceId);
            int row1 = carUseMapper.setInstanceId(param);
            if (row1!=1){
                throw new OAException("保存会议工作流失败");
            }
        }
        return row;
    }

    @Override
    public ArrayList<HashMap> selectOldLeaveListByCreator(HashMap param) {
        return carUseMapper.selectOldCarUseByCreater(param);
    }

    @Override
    public ArrayList<HashMap> selectLeaveListByCreator(HashMap param) {
        return carUseMapper.selectCarUseByCreater(param);
    }

    @Override
    public ArrayList<HashMap> selectCar() {
        return materialsMapper.selectCar();
    }

    @Override
    public HashMap selectCarUseById(int id) {
        return carUseMapper.selectCarUseById(id);
    }

    @Override
    public CarUse selectCarUseByUuid(String uuid) {
        return carUseMapper.selectCarUseByUuid(uuid);
    }

    @Override
    public int deleteByid(int id) {
        CarUse carUse = carUseMapper.myselectById(id);
        String instanceId = carUse.getInstanceId();
        approveService.deleteProcess(instanceId);
        return carUseMapper.deleteByid(id);
    }

    @Override
    public CarUse selectCarUseByInstanceId(String instanceId) {
        return carUseMapper.selectCarUseByInstanceId(instanceId);
    }

    @Override
    public void approveCarUseByInstanceId(String instanceId) {
        carUseMapper.approveCarUseByInstanceId(instanceId);
    }

    @Override
    public ArrayList<HashMap> searchCarUseInfo(HashMap param) {
        ArrayList<HashMap> hashMaps = carUseMapper.searchCarUseInfo(param);
        ArrayList<HashMap> usedlist=new ArrayList<>();
        hashMaps.forEach(d->{
            Date start = DateUtil.parseDate((String)d.get("startTime"));
            Date end = DateUtil.parseDate((String)d.get("endTime"));
            DateRange useRage=DateUtil.range(start,end,DateField.DAY_OF_MONTH);
            useRage.forEach(one->{
                String date = one.toString("yyyy-MM-dd");
                HashMap para=new HashMap<>();
                para.put("date", date);
                para.put("status","使用");
                para.put("reason",d.get("reason"));
                para.put("dept",d.get("dept"));
                para.put("username",d.get("username"));
                usedlist.add(para);
            });
        });
        ArrayList<HashMap> list=new ArrayList<>();
        DateRange range=DateUtil.range((DateTime)param.get("startTime"),(DateTime)param.get("endTime"), DateField.DAY_OF_MONTH);
        range.forEach(one->{
            String date = one.toString("yyyy-MM-dd");
            String type="未用";
            String userName="";
            String reason="";
            String dept="";
            for(HashMap map:usedlist){
                if (map.containsValue(date)) {
                    type="已用";
                    userName =(String) map.get("username");
                    dept = (String) map.get("dept");
                    reason = (String) map.get("reason");
                    break;
                }
            }
            HashMap result = new HashMap();
            result.put("date", date);
            result.put("type", type);
            result.put("username", userName);
            result.put("reason", reason);
            result.put("dept", dept);
            list.add(result);
        });
        return list;
    }

    public Boolean checkCarCanUse(CarUse carUse){
        HashMap param=new HashMap<>();
        param.put("startTime", carUse.getStartTime());
        param.put("endTime", carUse.getEndTime());
        param.put("carId", carUse.getCarId());
        ArrayList<HashMap> hashMaps = carUseMapper.searchCarUseInfo(param);
        if (hashMaps.size()>0){
            return false;
        }
        return true;
    }
}




